import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'  //静态导入

//路由懒加载
const Home = () => import(/* webpackChunkName: "Home" */ '../views/Home.vue')

const welcome = () => import(/* webpackChunkName: "Welcome" */ '../views/list/welcome.vue')
//用户模块
const Users = () => import(/* webpackChunkName: "Welcome" */ '../views/list/Users.vue')

//权限模块
const Rights = () => import(/* webpackChunkName: "Users_Rights_Roles" */ '../views/list/Rights.vue')

const Roles = () => import(/* webpackChunkName: "Users_Rights_Roles" */ '../views/list/Roles.vue')

//商品模块
const Categories = () => import(/* webpackChunkName: "Cate_Params" */ '../views/list/Categories.vue')

const Params = () => import(/* webpackChunkName: "Cate_Params" */ '../views/list/Params.vue')

//商品列表
const Goods = () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/list/Goods.vue')

const Goodss= () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/list/Goodss.vue')

//订单模块
const Orders = () => import(/* webpackChunkName: "Order_Report" */ '../views/list/Orders.vue')

const Reports = () => import(/* webpackChunkName: "Order_Report" */ '../views/list/Reports.vue')


Vue.use(VueRouter)

const routes = [
  {
    path: '/menu',
    name: 'Menu',
    component: () => import(/* webpackChunkName: "Test" */ '../views/Menu.vue'),
  },
  //项目正式路由开始
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', name: 'welcome',component: welcome},
      // { path: '/users',name: 'Users',component: Users},
      // { path: '/rights', component: Rights },
      // { path: '/roles', component: Roles },
      // { path: '/categories', component: Categories },
      // { path: '/params', component: Params },
      // { path: '/goods', component: Goods },
      { path: '/goodss', component: Goodss },
      // { path: '/orders', component: Orders },
      // { path: '/reports', component: Reports }

    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  
  {
    path: '*',
    redirect: '/login'
  },
]
const router = new VueRouter({
  routes
})


import {fn} from '@/utils/routeList.js'; //生成列表结构路由方法

//生成动态路由-登录后获取到路由列表
 function loadRoute() {
  let token = localStorage.getItem('token')
  let menusList=JSON.parse(localStorage.getItem('menusList'))
  if (token && menusList) {
      let newList = fn(menusList)
      newList.forEach(item => {
          router.addRoute("Home", item)
      })
  }
}

loadRoute()



const whiteList = ['/login','/menu']

//路由拦截
router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('token')
    if (token) {
        next()
    }
    else {
        if (whiteList.indexOf(to.path) != -1) {
            next()
        }
        else {
            next('/login')
        }
    }
})



export default router
